<script setup>
import {ref, watch} from 'vue'

//问题
const question = ref('')

//答案
const answer = ref('Questions usually contain a question mark. ;-)')

const loading = ref(false)

// 可以直接侦听一个 ref
watch(question, async (newQuestion, oldQuestion) => {
  console.log('侦听question开始')
  if (newQuestion.includes('?')) {
    loading.value = true
    answer.value = 'Thinking...'
    try {
      const res = await fetch('https://yesno.wtf/api')
      answer.value = (await res.json()).answer
    } catch (error) {
      answer.value = '出错了，请检查API接口. ' + error
    } finally {
      loading.value = false
    }
  }
  console.log('侦听question结束')
})
</script>

<template>
  <p>
    Ask a yes/no question:
    <input v-model="question" :disabled="loading"/>
  </p>
  <p>{{ answer }}</p>
</template>
